﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Admin.NET.Application;

/// <summary>
/// 货品类型服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class GoodstypeService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Goodstype> _goodstypeRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public GoodstypeService(SqlSugarRepository<Goodstype> goodstypeRep, ISqlSugarClient sqlSugarClient)
    {
        _goodstypeRep = goodstypeRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询货品类型 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询货品类型")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<GoodstypeOutput>> Page(PageGoodstypeInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _goodstypeRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.GoodsCode.Contains(input.Keyword) || u.GoodsName.Contains(input.Keyword) || u.Remark.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.GoodsCode), u => u.GoodsCode.Contains(input.GoodsCode.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.GoodsName), u => u.GoodsName.Contains(input.GoodsName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Remark), u => u.Remark.Contains(input.Remark.Trim()))
            .WhereIF(input.Sort != null, u => u.Sort == input.Sort)
            .LeftJoin<Goodstype>((u, parent) => u.ParentID == parent.Id)
            .Select((u, parent) => new GoodstypeOutput
            {
                Id = u.Id,
                ParentID = u.ParentID,
                ParentDisplayName = $"{parent.GoodsName}",
                GoodsCode = u.GoodsCode,
                GoodsName = u.GoodsName,
                Sort = u.Sort,
                State = u.State,
                Remark = u.Remark,
                IsDelete = u.IsDelete,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取货品类型详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取货品类型详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<Goodstype> Detail([FromQuery] QueryByIdGoodstypeInput input)
    {
        return await _goodstypeRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加货品类型 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加货品类型")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddGoodstypeInput input)
    {
        var entity = input.Adapt<Goodstype>();
        return await _goodstypeRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新货品类型 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新货品类型")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateGoodstypeInput input)
    {
        var entity = input.Adapt<Goodstype>();
        await _goodstypeRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除货品类型 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除货品类型")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteGoodstypeInput input)
    {
        var entity = await _goodstypeRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _goodstypeRep.FakeDeleteAsync(entity);   //假删除
        //await _goodstypeRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除货品类型 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除货品类型")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteGoodstypeInput> input)
    {
        var exp = Expressionable.Create<Goodstype>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _goodstypeRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _goodstypeRep.FakeDeleteAsync(list);   //假删除
        //return await _goodstypeRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataGoodstypeInput input)
    {
        var parentIDData = await _goodstypeRep.Context.Queryable<Goodstype>()
            .Select(u => new TreeParentOutputs {
                Value = u.Id,
                Label = $"{u.GoodsName}",
                Children=null
            }, true).ToTreeAsync(u => u.Children, u => u.ParentID, null);
        foreach (var item in parentIDData)
        {
            item.Children = await GetChildren(item.Value);
        }
        return new Dictionary<string, dynamic>
        {
            { "parentID", parentIDData },
        };
    }

    private async Task<List<TreeParentOutputs>> GetChildren(long? parentID)
    {
        var data = await _goodstypeRep.Context.Queryable<Goodstype>()
            .Where(u => u.ParentID == parentID)
            .Select(u => new TreeParentOutputs
            {
                Value = u.Id,
                Label = $"{u.GoodsName}",
            }).ToListAsync();
        foreach (var item in data)
        {
            item.Children = await GetChildren(item.Value);
        }
        return data;
    }

    /// <summary>
    /// 导出货品类型记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出货品类型记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageGoodstypeInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportGoodstypeOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "货品类型导出记录");
    }
    
    /// <summary>
    /// 下载货品类型数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载货品类型数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportGoodstypeOutput>(), "货品类型导入模板", (_, info) =>
        {
            if (nameof(ExportGoodstypeOutput.ParentDisplayName) == info.Name) return _goodstypeRep.Context.Queryable<Goodstype>().Select(u => $"{u.GoodsName}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入货品类型记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入货品类型记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportGoodstypeInput, Goodstype>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 父级ID
                    var parentIDLabelList = pageItems.Where(x => x.ParentDisplayName != null).Select(x => x.ParentDisplayName).Distinct().ToList();
                    if (parentIDLabelList.Any()) {
                        var parentIDLinkMap = _goodstypeRep.Context.Queryable<Goodstype>().Where(u => parentIDLabelList.Contains($"{u.GoodsName}")).ToList().ToDictionary(u => $"{u.GoodsName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.ParentID = parentIDLinkMap.GetValueOrDefault(e.ParentDisplayName ?? "");
                            if (e.ParentID == null) e.Error = "父级ID链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.Sort == null){
                            x.Error = "排序不能为空";
                            return false;
                        }
                        return true;
                    }).Adapt<List<Goodstype>>();
                    
                    var storageable = _goodstypeRep.Context.Storageable(rows)
                        .SplitError(it => string.IsNullOrWhiteSpace(it.Item.GoodsCode), "货品类型编号不能为空")
                        .SplitError(it => it.Item.GoodsCode?.Length > 32, "货品类型编号长度不能超过32个字符")
                        .SplitError(it => string.IsNullOrWhiteSpace(it.Item.GoodsName), "货品类型名称不能为空")
                        .SplitError(it => it.Item.GoodsName?.Length > 32, "货品类型名称长度不能超过32个字符")
                        .SplitError(it => it.Item.Sort == null, "排序不能为空")
                        .SplitError(it => it.Item.Remark?.Length > 300, "备注长度不能超过300个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
